package www.dianbaozu.com.ui.find.recommendationServer

import android.os.Bundle
import android.view.View
import androidx.annotation.NonNull
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.loadinghelper.LoadingHelper
import com.dylanc.loadinghelper.ViewType
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentRecommendationServerBinding
import www.dianbaozu.com.extension.requestServerDetails
import www.dianbaozu.com.ui.find.recommendationServer.adapter.RecommendationServerAdapter
import www.wen.com.common.lib.base.fragment.BaseListFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.extension.nav
import www.wen.com.common.lib.extension.observeObject
import www.wen.com.common.lib.extension.postObject
import www.wen.com.common.lib.helper.loading.FindModuleAdapter
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.INSERT_PREVIEW_SERVER_KEY
import www.wen.com.common.lib.helper.loading.KeyHelper.MAIN_VIEWPAGER_POSITION_KEY
import www.wen.com.common.lib.helper.loading.LoadingAdapter
import www.wen.com.common.lib.util.DisplayUtil
import www.wen.com.common.lib.view.SpaceItemDecoration

/**
 * @author WEN
 * @Description:主页发现 - 推荐服务器列表
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class RecommendationServerFragment :
        BaseListFragment<FragmentRecommendationServerBinding, ServerEntity, ServerEntity>(),
        View.OnClickListener {

    private lateinit var mAdapter: RecommendationServerAdapter

    private val recommendationServerViewModel: RecommendationServerViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = recommendationServerViewModel

    override val mRecyclerView: RecyclerView
        get() = dataBinding.rvRecommendedServer

    override val mSmartRefreshLayout: SmartRefreshLayout
        get() = dataBinding.smartRefreshLayout

    override fun provideAdapter(): BaseQuickAdapter<ServerEntity, BaseViewHolder> =
            RecommendationServerAdapter().apply {
                mAdapter = this
            }

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): FindModuleAdapter = FindModuleAdapter(requireActivity(), true, action = ::titleAction)

    override fun actionRight() {
        nav(R.id.action_mainFragment_to_searchServerFragment)
    }

    override fun provideLayoutManager(): RecyclerView.LayoutManager =
            GridLayoutManager(context, 2)

    override val isAddItemDecoration: Boolean
        get() = true

    override fun provideItemDecoration(): RecyclerView.ItemDecoration =
            SpaceItemDecoration(DisplayUtil.dip2px(8f).toInt(), 2)

    override fun configurationLoadingHelper(loadingHelper: LoadingHelper): LoadingHelper {
        loadingHelper.register(ViewType.LOADING, LoadingAdapter(R.color.color1B1D22))
        loadingHelper.register(ViewType.TITLE, getTitleBarUniversalAdapter())
        loadingHelper.setDecorHeader(ViewType.TITLE)
        return loadingHelper
    }

    override fun getLayoutId(): Int = R.layout.fragment_recommendation_server

    override fun lazyInitView() {
        super.lazyInitView()
        observeListen()
        launchRequest(false)
    }

    private fun observeListen() {
        recommendationServerViewModel.uiState.observe(this) {
            if (it.showSuccess != null) {
                if (it.isRefresh) {
                    mAdapter.setList(it.showSuccess)
                } else {
                    mAdapter.addData(it.showSuccess!!)
                }
            }
        }
        //更新服务器名字、logo、背景、简介
        observeObject(
                KeyHelper.UPDATE_SERVER_INFORMATION_KEY,
                this,
                ServerUpdateInfoEntity::class.java
        ) {

            if (serverId.isNullOrBlank()) return@observeObject

            val appointServerIndex = mAdapter.data.indexOfFirst { it.serverId == serverId }
            if (appointServerIndex != -1) {
                serverName?.also { mAdapter.data[appointServerIndex].serverName = it }
                serverLogo?.also { mAdapter.data[appointServerIndex].serverLogo = it }
                serverBackground?.also { mAdapter.data[appointServerIndex].serverBackground = it }
                serverIntro?.also { mAdapter.data[appointServerIndex].serverIntro = it }
                mAdapter.notifyItemChanged(appointServerIndex)
            }
        }
    }

    override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {
        launchRequest(true)
    }

    override fun onLoadMore() {
        launchRequest(false)
    }

    private fun launchRequest(isRefresh: Boolean) {
        recommendationServerViewModel.requestGeneralListData(requiredParameter = RequestBodyParameter(), isRefresh = isRefresh)
    }

    override fun onReload() {
        launchRequest(false)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val data = adapter.data[position] as ServerEntity
        recommendationServerViewModel.requestServerDetails(
                viewModelScope = lifecycleScope,
                data.serverId,
        ) { serverInfo ->
            if (serverInfo.serverMember != null) {
                serverInfo.fromType = NavigationFromType.FROM_RECOMMENDATION
                nav(R.id.action_mainFragment_to_serverDetailsFragment, Bundle().apply {
                    putParcelable(BUNDLE_DATA, serverInfo)
                })
            } else {
                recommendationServerViewModel.requestServerPreview(data.serverId) {
                    postObject(INSERT_PREVIEW_SERVER_KEY, it)
                    postObject(MAIN_VIEWPAGER_POSITION_KEY, ViewPagePosition(0))
                }
            }
        }
    }

}



